package com.ctaa.login;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.common.pojo.dto.Result;
import com.common.utils.ConstantsUrl;
import com.common.utils.MD5Utils;
import com.common.utils.ValidationUtils;
import com.ctaa.R;
import com.ctaa.databinding.ActivityRegisterBinding;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class RegisterActivity extends AppCompatActivity {

    private ActivityRegisterBinding registerBinding;

    private boolean passwordVisible = false;
    private boolean confirmPasswordVisible = false;

    private EditText userName, email, password, confirmPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBinding = ActivityRegisterBinding.inflate(getLayoutInflater());
        setContentView(registerBinding.getRoot());
        userName = registerBinding.usernameEditText;
        email = registerBinding.emailEditText;
        password = registerBinding.passwordEditText;
        confirmPassword = registerBinding.confirmPasswordEditText;

        // 初始化返回按钮
        registerBinding.backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回登录页面
                onBackPressed();
                // 添加过渡动画
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            }
        });

        // 已有账户，返回登录
        registerBinding.loginTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回登录页面
                onBackPressed();
                // 添加过渡动画
                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
            }
        });

        //点击密码眼睛
        registerBinding.togglePasswordVisibility.setOnClickListener(v -> {
            passwordVisible = !passwordVisible;
            if (passwordVisible) {
                // 显示密码
                registerBinding.passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                registerBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye);
            } else {
                // 隐藏密码
                registerBinding.passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                registerBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
            }

            // 光标定位到文本末尾
            registerBinding.passwordEditText.setSelection(registerBinding.passwordEditText.getText().length());

        });
        //点击再次确认密码眼睛
        registerBinding.toggleConfirmPasswordVisibility.setOnClickListener(v -> {
            confirmPasswordVisible = !confirmPasswordVisible;
            if (confirmPasswordVisible) {
                // 显示密码
                registerBinding.confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                registerBinding.toggleConfirmPasswordVisibility.setImageResource(R.drawable.ic_eye);
            } else {
                // 隐藏密码
                registerBinding.confirmPasswordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                registerBinding.toggleConfirmPasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
            }

            // 光标定位到文本末尾
            registerBinding.confirmPasswordEditText.setSelection(registerBinding.confirmPasswordEditText.getText().length());

        });


        //点击服务条款
        registerBinding.termsTextView.setOnClickListener(v -> {
            showToast("点击服务条款");
        });

        //点击隐私政策
        registerBinding.privacyTextView.setOnClickListener(v -> {
            showToast("点击隐私政策");
        });

        //点击注册按钮
        registerBinding.registerButton.setOnClickListener(v -> {
            String userNameStr = userName.getText().toString();
            String emailStr = email.getText().toString();
            String passwordStr = password.getText().toString();
            String confirmPasswordStr = confirmPassword.getText().toString();

            if (userNameStr == null || "".equalsIgnoreCase(userNameStr)) {
                showToast("用户名不能为空");
                return;
            }
            if (emailStr == null || "".equalsIgnoreCase(emailStr)) {
                showToast("邮箱不能为空");
                return;
            }
            boolean validEmail = ValidationUtils.isValidEmail(emailStr);
            if (!validEmail) {
                showToast("邮箱格式不正确");
                return;
            }
            if (passwordStr == null || "".equalsIgnoreCase(passwordStr)) {
                showToast("密码不能为空");
                return;
            }
            if (confirmPasswordStr == null || "".equalsIgnoreCase(confirmPasswordStr)) {
                showToast("确认密码不能为空");
                return;
            }
            if (!passwordStr.equalsIgnoreCase(confirmPasswordStr)) {
                showToast("两次密码不相同");
                return;
            }

            CheckBox termsCheckbox = registerBinding.termsCheckbox;
            if (!termsCheckbox.isChecked()) {
                showToast("请同意协议");
                return;
            }

            regisBtn("正在注册...");
            OkHttpUtils.get().url(ConstantsUrl.registUrl)
                    .addParams("userName", userNameStr)
                    .addParams("password", MD5Utils.encrypt(passwordStr))
                    .addParams("email", emailStr)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    if (e instanceof java.net.SocketTimeoutException) {
                        showToast("网络连接超时，请检查网络设置");
                    } else if (e instanceof java.io.IOException) {
                        showToast("网络请求失败，请检查网络连接");
                    } else {
                        showToast("网络请求出现未知错误");
                    }
                    regisBtn("注册");
                }

                @Override
                public void onResponse(String response, int id) {
                    regisBtn("注册");
                    Result result = null;
                    try {
                        result = JSONObject.parseObject(response, Result.class);
                    } catch (Exception e) {
                    }
                    if (result == null) {
                        result = Result.fail("注册请求返回失败");
                    }
                    showToast(result.getMessage());
                }
            });

        });

    }

    //注册按钮修改
    private void regisBtn(String message) {
        registerBinding.registerButton.setText(message);
    }

    private void showToast(String content) {
        runOnUiThread(() -> {
            Toast.makeText(RegisterActivity.this, content, Toast.LENGTH_SHORT).show();
        });
    }
}